package cn.t.service;


import cn.t.constants.CommonConstants;
import cn.t.core.service.ServiceImpl;
import cn.t.enums.order.WorkStatusEnum;
import cn.t.model.IndustryUserInfoDO;
import cn.t.model.order.WorkOrderDO;
import cn.t.repository.IndustryUserInfoRepository;
import cn.t.service.order.WorkOrderService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户留资表领域服务
 */
@Slf4j
@Service
@AllArgsConstructor
public class IndustryUserInfoService extends ServiceImpl<IndustryUserInfoDO, IndustryUserInfoRepository> {

    private final WorkOrderService workOrderService;

    // 根据手机号查询用户留资信息
    public IndustryUserInfoDO getIndustryUserInfo(String phoneNumber) {

        if (!StringUtils.hasText(phoneNumber)) {
            return null;
        }

        IndustryUserInfoDO queryParams = new IndustryUserInfoDO();
        queryParams.setPhoneNumber(phoneNumber);
        // 优先取后留资用户
        List<IndustryUserInfoDO> industryUserInfos = this.findByModel(queryParams, CommonConstants.ZERO, Integer.MAX_VALUE, "id", "desc");
        // 过滤掉尾数不是 phoneNumber 的手机号
        industryUserInfos = industryUserInfos.stream().filter(f -> f.getPhoneNumber().substring(CommonConstants.ELEVEN - phoneNumber.length()).equals(phoneNumber)).collect(Collectors.toList());

        // 对手机号后4位可能会重复的情况进行优化
        if (industryUserInfos.size() > 1) {
            List<String> workOrderSns = industryUserInfos.stream().map(IndustryUserInfoDO::getWorkOrderSn).collect(Collectors.toList());
            WorkOrderDO queryParam = new WorkOrderDO();
            queryParam.setWorkOrderSns(workOrderSns);
            queryParam.setStatus(WorkStatusEnum.WAIT_DO.getCode());
            // 优先取后生成的工单
            List<WorkOrderDO> workOrders = this.workOrderService.findByModel(queryParam, CommonConstants.ZERO, Integer.MAX_VALUE, "id", "desc");
            // 有未领礼品的情况
            if (!CollectionUtils.isEmpty(workOrders)) {
                return industryUserInfos.stream().filter(f -> workOrders.get(0).getWorkOrderSn().equals(f.getWorkOrderSn())).findFirst().orElse(null);
            }
        }
        // 无未领礼品的情况
        return CollectionUtils.isEmpty(industryUserInfos) ? null : industryUserInfos.get(0);
    }
}
